//
//  UserAccountManager.m
//  QiFuLianMeng
//
//  Created by yuntai on 2017/5/5.
//  Copyright © 2017年 yuntai. All rights reserved.
//

#import "UserAccountManager.h"
#import "AppDelegate.h"
#import "AppDelegate.h"
#import "AppDelegate+Extension.h"
#import "ViewController.h"

@implementation UserAccountManager
static UserAccountManager * manager;

+ (instancetype)shareUserAccountManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[UserAccountManager alloc] init];

    });
    return manager;
}
- (instancetype)init
{
    self = [super init];
    
    if(!self) return nil;
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary * userDic = [userDefaults objectForKey:kLoginStageKey];
    if(userDic)
    {
        _userModel = [UserModel mj_objectWithKeyValues:userDic];
        _loginStatus = YES;
    }
    return self;
}
- (void)loginWithModel:(UserModel *)user
{
    _userModel = user;
    _loginStatus = YES;
    [self saveAccountDefaults];
}
- (void)loginWithUserDic:(NSDictionary *)userDic
{
    _loginStatus = YES;
    if (userDic.allKeys.count) {
        UserModel * userModel = [UserModel mj_objectWithKeyValues:userDic];
        _userModel = userModel;
        _loginStatus = YES;
        [self saveAccountDefaults];
    }
    [kUserDefault setBool:YES forKey:kUserIsLogin];
    [kUserDefault setObject:_userModel.token?:@"" forKey:kTokenDefaultKey];
    [kUserDefault setObject:_userModel.userName?:@"" forKey:kVersionLoginName];
    [kUserDefault setObject:_userModel.userId?:@"" forKey:kVersionLoginID];
    [kUserDefault synchronize];
    [AppDelegate appDelegate].window.rootViewController = [[AppDelegate appDelegate] changeRootViewController];
}
- (void)saveAccountWith:(NSDictionary *)dic{
    _loginStatus = YES;
    if (dic.allKeys.count) {
        UserModel * userModel = [UserModel mj_objectWithKeyValues:dic];
        _userModel = userModel;
        [self saveAccountDefaults];
    }
    [kUserDefault setBool:YES forKey:kUserIsLogin];
    [kUserDefault synchronize];
}
- (void)logout
{
    _userModel = nil;
    [kUserDefault setBool:NO forKey:kUserIsLogin];
    [kUserDefault setObject:@"" forKey:kVersionLoginID];
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"kDefaultH5Token"];
    [kUserDefault synchronize];

    ViewController *login = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle] ]instantiateViewControllerWithIdentifier:@"LoginVC"];
   [AppDelegate appDelegate].window.rootViewController = login;
    [self removeAccountDefaults];
}

#pragma mark - private
/**
 *  保存用户信息至NSUserDefaults
 */
- (void)saveAccountDefaults
{
    if(!_loginStatus)
    {
        return;
    }
    NSDictionary * dic = [_userModel mj_keyValues];
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:dic forKey:kLoginStageKey];
    [kUserDefault synchronize];

}
/**
 *  删除NSUserDefaults中的用户信息
 */
- (void)removeAccountDefaults
{
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:kLoginStageKey];
    [kUserDefault synchronize];
    _loginStatus = NO;
    
}



//-(void)getAliClientCompletion:(OSSClientCompleted)completion
//{
////    [kUserDefault setObject:@"xxxxxxxxxxxx" forKey:AliCloudOSSToken];
////    [kUserDefault setObject:@"" forKey:AliCloudOSSExpiration];
////    [kUserDefault setObject:@"LTAIRPgFINEgrCBi" forKey:AliCloudOSSAccessKeyId];
////    [kUserDefault setObject:@"naJiioeUOzkf78k7NKHBmnyc5duGzP" forKey:AliCloudOSSAccessKeySecret];
////    [kUserDefault synchronize];
//
//    if (![[NSUserDefaults standardUserDefaults] objectForKey:AliCloudOSSToken]) {
//        [self reloadTokenCompletion:^(NSError *error) {
//            if (!error) {
//                completion([self initializeOSSClient],YES);
//
//            }
//            else
//            {
//                completion(nil,NO);
//            }
//        }];
//    }
//    else
//    {
//        NSString * timeStamp = [[NSUserDefaults standardUserDefaults] objectForKey:AliCloudOSSExpiration];
//        timeStamp = [[timeStamp stringByReplacingOccurrencesOfString:@"T" withString:@" "] stringByReplacingOccurrencesOfString:@"Z" withString:@""];
//        NSInteger newTimeStamp = [self timeSwitchTimestamp:timeStamp andFormatter:@"YYYY-MM-dd HH:mm:ss"];
//        NSInteger nowTimeStamp = [self getNowTimestamp];
//        if ( newTimeStamp < nowTimeStamp + 15 * 64) {
//            [self reloadTokenCompletion:^(NSError *error) {
//                if (!error) {
//                    completion([self initializeOSSClient],YES);
//                }
//                else
//                {
//                    completion(nil,NO);
//                }
//            }];
//        }
//        else
//        {
//            DDLog(@"没过期：还剩：%ld 分钟",(nowTimeStamp - newTimeStamp)/60);
//            completion([self initializeOSSClient],YES);
//        }
//    }
//}
-(NSInteger)getNowTimestamp{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间
    
    NSLog(@"设备当前的时间:%@",[formatter stringFromDate:datenow]);
    
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[datenow timeIntervalSince1970]] integerValue];
    
    NSLog(@"设备当前的时间戳:%ld",(long)timeSp); //时间戳的值
    
    return timeSp;
    
}

-(NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:format]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:formatTime];
    
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    
    NSLog(@"将某个时间转化成 时间戳&&&&&&&timeSp:%ld",(long)timeSp); //时间戳的值
    
    return timeSp;
    
}
//-(void)reloadTokenCompletion:(void(^)(NSError *error))completion
//{
//    [RequestTool getAliOSSTokenCompletion:^(NSString *tips, NSError *error, NSDictionary * response) {
//        if (!error)
//        {
//            NSString * aTokenJson = response[@"dataObj"][@"token"];
//            NSData *jsonData = [aTokenJson dataUsingEncoding:NSUTF8StringEncoding];
//            NSError *err;
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
//                                                                options:NSJSONReadingMutableContainers
//                                                                  error:&err];
//            if(err)
//            {
//                NSLog(@"json解析失败：%@",err);
//                if (completion) {
//                    completion(err);
//                }
//            }
//            else
//            {
//                NSString * AccessKeyId = dic[@"Credentials"][@"AccessKeyId"];
//                NSString * AccessKeySecret = dic[@"Credentials"][@"AccessKeySecret"];
//                NSString * Expiration = dic[@"Credentials"][@"Expiration"];
//                NSString * SecurityToken = dic[@"Credentials"][@"SecurityToken"];
//                NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
//                [defaults setObject:AccessKeyId forKey:AliCloudOSSAccessKeyId];
//                [defaults setObject:AccessKeySecret forKey:AliCloudOSSAccessKeySecret];
//                [defaults setObject:Expiration forKey:AliCloudOSSExpiration];
//                [defaults setObject:SecurityToken forKey:AliCloudOSSToken];
//                [defaults synchronize];
//                if (completion) {
//                    completion(nil);
//                }
//                
//            }
//            
//        }
//        else
//        {
//            if (completion) {
//                completion(error);
//            }
//        }
//    }];
//}
//-(OSSClient *)initializeOSSClient
//{
//    
//    NSString *endpoint = OSSBucketHost;
//    // 移动端建议使用STS方式初始化OSSClient。可以通过sample中STS使用说明了解更多(https://github.com/aliyun/aliyun-oss-ios-sdk/tree/master/DemoByOC)
//    NSString * AccessKeySecret = [[NSUserDefaults standardUserDefaults] objectForKey:AliCloudOSSAccessKeySecret];
//    NSString * SecurityToken = [[NSUserDefaults standardUserDefaults] objectForKey:AliCloudOSSToken];
//    NSString * AccessKeyId = [[NSUserDefaults standardUserDefaults] objectForKey:AliCloudOSSAccessKeyId];
//    
//    
////    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKeyId secretKey:AccessKeySecret];
////    OSSClient * client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
////    return client;
//    
//    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:AccessKeyId secretKeyId:AccessKeySecret securityToken:SecurityToken];
//    return [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
//    
//}

@end
